/*
 * wxcharts.js v1.0
 * 微信小程序图表工具
 * 支持饼图、柱状图等
 */

class WxCharts {
  constructor(opts) {
    this.opts = opts;
    this.context = wx.createCanvasContext(opts.canvasId, opts.componentInstance);
    this.chartData = opts.data || {};
    this.config = {
      fontSize: opts.fontSize || 12,
      titleFontSize: opts.titleFontSize || 16,
      titleColor: opts.titleColor || '#333333',
      padding: opts.padding || 10,
      colors: opts.colors || ['#07c160', '#10b981', '#34d399', '#60a5fa', '#818cf8', '#a78bfa', '#c084fc', '#f472b6', '#fb7185', '#fbbf24'],
      backgroundColor: opts.backgroundColor || '#ffffff',
      width: opts.width || 300,
      height: opts.height || 200,
      dataLabel: opts.dataLabel !== false,
      animation: opts.animation !== false,
      animationDuration: opts.animationDuration || 1000,
      title: opts.title || '',
      subtitle: opts.subtitle || '',
      legend: opts.legend !== false,
      legendPosition: opts.legendPosition || 'bottom',
      legendItemWidth: opts.legendItemWidth || 15,
      legendItemHeight: opts.legendItemHeight || 15,
      legendMargin: opts.legendMargin || 5,
      legendFontSize: opts.legendFontSize || 12,
      legendFontColor: opts.legendFontColor || '#666666',
    };
    this.init();
  }

  init() {
    const { width, height, backgroundColor } = this.config;
    this.context.setFillStyle(backgroundColor);
    this.context.fillRect(0, 0, width, height);
  }

  drawPieChart() {
    const { padding, width, height, colors, dataLabel, animation, title, titleFontSize, titleColor } = this.config;
    const series = this.chartData.series || [];
    const total = series.reduce((sum, item) => sum + item.data, 0);
    const radius = Math.min(width, height) / 2 - padding * 2;
    const centerX = width / 2;
    const centerY = height / 2;

    // 绘制标题
    if (title) {
      this.context.setFontSize(titleFontSize);
      this.context.setFillStyle(titleColor);
      this.context.setTextAlign('center');
      this.context.fillText(title, centerX, padding + titleFontSize);
    }

    // 绘制饼图
    let startAngle = 0;
    series.forEach((item, index) => {
      const portion = item.data / total;
      const endAngle = startAngle + portion * 2 * Math.PI;
      
      // 绘制扇形
      this.context.beginPath();
      this.context.moveTo(centerX, centerY);
      this.context.arc(centerX, centerY, radius, startAngle, endAngle);
      this.context.setFillStyle(colors[index % colors.length]);
      this.context.fill();
      
      // 绘制标签
      if (dataLabel) {
        const midAngle = startAngle + (endAngle - startAngle) / 2;
        const labelRadius = radius * 0.7;
        const labelX = centerX + Math.cos(midAngle) * labelRadius;
        const labelY = centerY + Math.sin(midAngle) * labelRadius;
        
        this.context.setFontSize(12);
        this.context.setFillStyle('#ffffff');
        this.context.setTextAlign('center');
        this.context.setTextBaseline('middle');
        this.context.fillText(item.name, labelX, labelY);
      }
      
      startAngle = endAngle;
    });

    // 绘制图例
    if (this.config.legend) {
      this.drawLegend(series);
    }

    this.context.draw(true);
  }

  drawColumnChart() {
    const { padding, width, height, colors, dataLabel, title, titleFontSize, titleColor } = this.config;
    const categories = this.chartData.categories || [];
    const series = this.chartData.series || [];
    
    // 计算图表区域
    const titleHeight = title ? titleFontSize + padding : 0;
    const chartArea = {
      x: padding * 2,
      y: titleHeight + padding,
      width: width - padding * 4,
      height: height - titleHeight - padding * 3
    };
    
    // 绘制标题
    if (title) {
      this.context.setFontSize(titleFontSize);
      this.context.setFillStyle(titleColor);
      this.context.setTextAlign('center');
      this.context.fillText(title, width / 2, padding + titleFontSize);
    }
    
    // 绘制坐标轴
    this.context.beginPath();
    this.context.setStrokeStyle('#cccccc');
    this.context.setLineWidth(1);
    this.context.moveTo(chartArea.x, chartArea.y + chartArea.height);
    this.context.lineTo(chartArea.x + chartArea.width, chartArea.y + chartArea.height);
    this.context.stroke();
    
    // 计算柱状图宽度和间距
    const columnCount = categories.length;
    const columnWidth = chartArea.width / columnCount * 0.6;
    const columnSpacing = chartArea.width / columnCount * 0.4;
    
    // 找出最大值，用于计算高度比例
    const maxValue = Math.max(...series.map(item => Math.max(...item.data)));
    const heightRatio = chartArea.height / maxValue;
    
    // 绘制柱状图
    series.forEach((serie, serieIndex) => {
      const color = colors[serieIndex % colors.length];
      
      serie.data.forEach((value, index) => {
        const x = chartArea.x + (columnWidth + columnSpacing) * index + columnSpacing / 2;
        const columnHeight = value * heightRatio;
        const y = chartArea.y + chartArea.height - columnHeight;
        
        // 绘制柱子
        this.context.setFillStyle(color);
        this.context.fillRect(x, y, columnWidth, columnHeight);
        
        // 绘制数值标签
        if (dataLabel) {
          this.context.setFontSize(12);
          this.context.setFillStyle('#666666');
          this.context.setTextAlign('center');
          this.context.fillText(value.toString(), x + columnWidth / 2, y - 5);
        }
      });
    });
    
    // 绘制X轴标签
    categories.forEach((category, index) => {
      const x = chartArea.x + (columnWidth + columnSpacing) * index + columnWidth / 2 + columnSpacing / 2;
      const y = chartArea.y + chartArea.height + padding;
      
      this.context.setFontSize(12);
      this.context.setFillStyle('#666666');
      this.context.setTextAlign('center');
      this.context.fillText(category, x, y);
    });
    
    // 绘制图例
    if (this.config.legend && series.length > 1) {
      this.drawLegend(series);
    }
    
    this.context.draw(true);
  }

  drawLegend(series) {
    const { legendPosition, legendItemWidth, legendItemHeight, legendMargin, legendFontSize, legendFontColor, colors, width, height, padding } = this.config;
    
    const legendWidth = series.reduce((sum, item) => {
      return sum + legendItemWidth + legendMargin * 2 + this.measureText(item.name, legendFontSize) + legendMargin * 2;
    }, 0);
    
    let startX = (width - legendWidth) / 2;
    let startY = height - legendItemHeight - padding;
    
    if (legendPosition === 'top') {
      startY = padding;
    }
    
    series.forEach((item, index) => {
      // 绘制图例颜色块
      this.context.setFillStyle(colors[index % colors.length]);
      this.context.fillRect(startX, startY, legendItemWidth, legendItemHeight);
      
      // 绘制图例文字
      this.context.setFontSize(legendFontSize);
      this.context.setFillStyle(legendFontColor);
      this.context.setTextAlign('left');
      this.context.setTextBaseline('middle');
      this.context.fillText(item.name, startX + legendItemWidth + legendMargin, startY + legendItemHeight / 2);
      
      // 更新下一个图例的起始位置
      startX += legendItemWidth + legendMargin * 2 + this.measureText(item.name, legendFontSize) + legendMargin * 2;
    });
  }

  measureText(text, fontSize) {
    // 简单估算文本宽度
    return text.length * fontSize * 0.6;
  }
}

module.exports = {
  WxCharts
}; 